package com.ymm.system.core.mq.sender;

import com.alibaba.fastjson.JSON;
import com.ymm.system.core.constants.OrderOpsEnum;
import com.ymm.system.core.mq.msg.OrderCancelMsg;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@Component
public class OrderCancelMsgSender {
    @Resource
    private RocketMQTemplate rocketMqTemplate;

    @Value("${mq.topic.order}")
    private String topic;

    public void send(Long orderId, Long shipperId, Long driverId, Long cargoId, Integer opsPersonType, Long opsPersonId) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        OrderCancelMsg orderCancelMsg = new OrderCancelMsg();
        orderCancelMsg.setOrderId(orderId);
        orderCancelMsg.setShipperId(shipperId);
        orderCancelMsg.setDriverId(driverId);
        orderCancelMsg.setCargoId(cargoId);
        orderCancelMsg.setOpsPersonType(opsPersonType);
        orderCancelMsg.setOpsPersonId(opsPersonId);
        String keys = orderId + "|" + OrderOpsEnum.CANCEL.getCode();
        sendMessage(topic, "cancel", keys, JSON.toJSONString(orderCancelMsg));
    }

    private void sendMessage(String topic, String tag, String keys, String body) throws MQBrokerException, RemotingException, InterruptedException, MQClientException {
        Message message = new Message(topic, tag, keys, body.getBytes(StandardCharsets.UTF_8));
        SendResult send = rocketMqTemplate.getProducer().send(message);
    }
}
